<?php
/**
 * Created by PhpStorm
 *
 * @author  : yiyu
 * @time    : 2018/3/18 17:24
 * @desc    : admin模块基类
 * @fileName: AdminBaseController.php
 */

namespace app\admin\controller;

use think\Controller;
use app\core\exception\{BusinessException, ErrorCode};
use app\core\util\{JwtUtil, TokenUtil};
use app\core\log\Log4dd;

class AdminBaseController extends Controller
{

    /**
     * 返回正确的json格式
     *
     * @param array $data
     * @param string $msg
     */
    public function successReturn($data = null, $msg = '')
    {
        $errorNo = ErrorCode::COMMON_SUCCESS;
        $res = [
            'code' => $errorNo,
            'msg' => empty($msg) ? ErrorCode::ERROR_MSG[ErrorCode::COMMON_SUCCESS] : $msg,
            'time' => time(),
            'data' => $data
        ];

        $this->writeLog($errorNo, $res);

        return json($res);
    }

    /**
     * 错误返回json格式
     * @param int $errorNo
     * @param string $msg
     */
    public function errorReturn($errorNo = ErrorCode::COMMON_ERROR, $msg = '')
    {
        if (!is_numeric($errorNo)) {
            $errorNo = ErrorCode::COMMON_ERROR;
        }
        $code = empty($errorNo) ? ErrorCode::COMMON_ERROR : $errorNo;
        $res = [
            'code' => $code,
            'msg' => empty($msg) ? ErrorCode::ERROR_MSG[$code] : $msg,
            'time' => time()
        ];

        $this->writeLog($code, $res);

        return json($res);
    }

    /**
     * response记录接口请求的日志
     *
     * @param $handleCode
     * @param $response
     */
    private function writeLog($handleCode, $response)
    {
        $user_id = TokenUtil::getAdminIdByToken();
        $uri = $_SERVER['REQUEST_URI'];
        $startTime = $_SERVER['REQUEST_TIME_FLOAT'];
        $nowTime = microtime(true);
        $consumeTime = bcsub($nowTime, $startTime, 3) * 1000;

        $resData = [
            'Request' => $_REQUEST
        ];
        $resData['Service'] = [
            'user_agent' => $_SERVER['HTTP_USER_AGENT'],
            'method' => $_SERVER['REQUEST_METHOD'],
            'scheme' => $_SERVER['REQUEST_SCHEME'],
            'status' => $_SERVER['REDIRECT_STATUS'],
        ];
        // 只有错误请求时，才将响应包写入日志
        if ($handleCode !== ErrorCode::COMMON_SUCCESS) {
            $resData['Response'] = $response;
        }

        Log4dd::info($user_id, ['uri' => $uri, 'consumeTime' => $consumeTime, 'resData' => $resData]);
    }
}
